package cn.edu.zzuli.nothinglink.config.realm;

import cn.edu.zzuli.nothinglink.constant.TokenConst;
import cn.edu.zzuli.nothinglink.entity.JWTToken;
import cn.edu.zzuli.nothinglink.entity.Students;
import cn.edu.zzuli.nothinglink.mapper.StudentsMapper;
import cn.edu.zzuli.nothinglink.utils.TokenUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class StudentRealm extends AuthorizingRealm {

    @Resource
    StudentsMapper studentsMapper;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权 => stu_doGetAuthorizationInfo");
        //此时 principalCollection 放的是我们的token
        String token = principalCollection.toString();
        String role = TokenUtil.getRole(token);

        if (TokenConst.STU_ROLE.getKey().equals(role)) {
            //给资源进行授权
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //当前登录的对象,当然我们这里不需要授权。
            //Subject subject = SecurityUtils.getSubject();
            info.addRole("stu");
            return info;
        }

        return new SimpleAuthorizationInfo();
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证 => stu_doGetAuthorizationInfo");
        //我们自己对于token，已经自定义为 JWTToken 这个类了。
        String token= (String) authenticationToken.getCredentials();
        System.out.println(token);
        //我们封装在 token里的是id。所以我们直接id判断。
        String id= TokenUtil.getAccount(token);
        String role = TokenUtil.getRole(token);

        if (TokenConst.STU_ROLE.getKey().equals(role)) {
            //这里进行数据库校验
            Students student = studentsMapper.selectById(Integer.parseInt(id));
            if (student == null) return null;
            System.out.println("success");
            //判断密码 shiro 为了安全，不让我们去碰密码，所以我们需要在 在第二个参数中传入 密码对象
            //SimpleAuthenticationInfo 是 AuthenticationInfo的子类
            //甚至可以md5 加密
            return new SimpleAuthenticationInfo(token,token, this.getClass().getSimpleName());
        }

        return null;


    }

}
